package com.szy.integration.email;

import com.szy.system.error.exception.MailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

/**
 * @author : zhenyun.su
 * @comment : 提供发送邮件服务
 * @since : 2020/3/5
 */

@Deprecated
public class SzyMailService {
    private static final Logger logger = LoggerFactory.getLogger(SzyMailService.class);

    private JavaMailSenderImpl javaMailSenderImpl;

    public SzyMailService(JavaMailSenderImpl javaMailSenderImpl) {
        this.javaMailSenderImpl = javaMailSenderImpl;
    }

    @Value("${spring.mail.username}")
    private String fromMail;

    public Boolean sendSimpleMail(String toMail, String subject, String content){
        logger.debug("sendSimpleMail, according to {}", toMail);
        try{
            final SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromMail);
            message.setTo(toMail);
            message.setSubject(subject);
            message.setText(content);
            javaMailSenderImpl.send(message);
            logger.debug("sendSimpleMail, success {}", toMail);
            return true;
        }catch(Exception e){
            logger.debug("sendSimpleMail, exception: {}", e);
            return false;
        }
    }

    public void sendTextMail(String toMail, String subject, String content) throws MailException {
        sendMimeMail(toMail, subject, content, false);
    }

    public void sendHtmlMail(String toMail, String subject, String content) throws MailException {
        sendMimeMail(toMail, subject, content, true);
    }

    public void sendMimeMail(String toMail, String subject, String content, Boolean html) throws MailException {
        logger.debug("sendMimeMail, according to {}", toMail);
        try{
            final MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom(fromMail);
            message.setTo(toMail);
            message.setSubject(subject);
            message.setText(content, html);
            //上传附件
            //message.addAttachment();
            logger.debug("sendMimeMail, subject:{}, content: {} ", subject, content);
            javaMailSenderImpl.send(mimeMessage);
            logger.debug("sendMimeMail, success");
        }catch(Exception e){
            logger.debug("sendMimeMail, exception: {}", e);
            throw new MailException(e.getMessage());
        }
    }


}
